<template>
  <!-- TODO:组件化 -->
  <el-form ref="form" :rules="loginRules" :model="form">
    <el-col :span="24">
      <el-form-item prop="mobile">
        <el-input v-model="form.mobile" placeholder="请输入之前注册的手机号" @wheel.native.prevent="stopScrollFun($event)"
          oninput="if(value.length > 11) value=value.slice(0, 11)"
          @keydown.native="e => ( (e.ctrlKey || e.metaKey) && ['c', 'v'].includes(e.key.toLowerCase())) || /[0-9]/.test(e.key) || ['Backspace', 'Tab', 'ArrowLeft', 'ArrowRight', 'Enter', 'Delete'].includes(e.key) || e.preventDefault()"></el-input>
      </el-form-item>
    </el-col>
    <el-col :span="15">
      <el-form-item prop="code">
        <el-input v-model.trim="form.code" placeholder="请输入图形码" maxlength="4" @keyup.enter.native="handleSubmit"
          class="code_input" />
      </el-form-item>
    </el-col>
    <el-col :span="9">
      <div class="code">
        <img :src="imgPicture" alt="" @click="getPicture">
      </div>
    </el-col>
    <el-col :span="24">
      <el-form-item prop="sms_code">
        <el-input ref="sms_code" class="sms_code_input" v-model.trim="form.sms_code" placeholder="请输入验证码"
          name="sms_code" auto-complete="on" tabindex="4" type="number" @wheel.native.prevent="stopScrollFun($event)"
          oninput="if(value.length > 6) value=value.slice(0, 6)"
          @keydown.native="e=>e.returnValue=(['e','E','-','+'].includes(e.key))?false:e.returnValue">
          <template slot="append">
            <div class="sendCode">
              <el-button @click="getPhoneMsg(2)" :disabled="disabledVertify" type="text">
                {{codeInfoText}}</el-button>
            </div>
          </template>
        </el-input>
      </el-form-item>
    </el-col>
    <el-col :span="24">
      <el-form-item prop="password">
        <el-input v-model="form.password" placeholder="请输入新密码" @keyup.enter.native="handleSubmit"
          :class="{'passwordInput':true,'allBorder':!form.password}" ref="passwordInput" :maxlength="20"
          @input="handleInput" :type="inputType" @focus="passwordFocus=true">
          <template #append v-if="form.password">
            <div @click="togglePassword" class="password-toggle">
              <img :src="passwordShow? eyeOpenImg : eyeCloseImg" alt="切换密码显示" class="password-toggle-img">
            </div>
          </template>
        </el-input>
      </el-form-item>
    </el-col>
    <el-col :span="24" v-if="form.password||passwordFocus">
      <passwordStreng :password="form.password" />
    </el-col>
    <el-col :span="24">
      <el-form-item>
        <div class="bottombuttons">
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            确定
          </el-button>

          <div class="changeFormButtons">
            <p @click="changeForm('login')" class="changeForm">
              去登录
            </p>
          </div>
        </div>
      </el-form-item>
    </el-col>
  </el-form>
</template>

<script>
import {
  validUsername,
  validPassword,
  validChinesePhoneNumber,
} from "@/utils/validate";
import passwordStreng from "./passwordStreng.vue";
import { captchaInit, sendSms, loginResetPassword } from "@/api/user";
export default {
  name: "SaaSForgetForm",
  components: {
    passwordStreng,
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("账号密码有误"));
      }
      callback();
    };
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error("密码必须包含字母、数字、特殊符号且长度在8-20位"));
      }
      callback();
    };
    const validateChinesePhoneNumber = (rule, value, callback) => {
      if (!validChinesePhoneNumber(value)) {
        callback(new Error("请输入正确的手机号码"));
      }
      callback();
    };
    return {
      passwordFocus: false,
      eyeOpenImg: "//img3.job1001.com/data_center/images/eyeOpen.png",
      eyeCloseImg: "//img3.job1001.com/data_center/images/eyeClose.png",
      codeInfoText: "发送验证码",
      disabledVertify: false,
      disabledCatpchaFlash: false,
      captchaId: "",
      imgPicture: "",
      form: {
        username: "",
        password: "",
        mobile: "",
        code: "",
        sms_code: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        mobile: [
          {
            required: true,
            trigger: "blur",
            validator: validateChinesePhoneNumber,
          },
        ],
      },
      loading: false,
      passwordShow: false,
    };
  },
  computed: {
    inputType() {
      return this.passwordShow ? "text" : "password"; // 使用计算属性来动态返回类型
    },
  },
  created() {
    document.title = "找回密码";
    this.initCaptcha();
  },
  methods: {
    togglePassword() {
      this.passwordShow = !this.passwordShow;
      // 切换输入框类型
      this.$refs.passwordInput.type = this.passwordShow ? "text" : "password";
    },
    handleInput(value) {
      // 正则表达式：只允许英文字母、数字和特殊字符
      const validChars = value.replace(/[^a-zA-Z0-9._~!@#$^&*()\-+=]/g, "");

      // 将过滤后的内容更新到 password 中
      this.form.password = validChars;
    },
    changeForm(type) {
      this.$store.dispatch("user/setSaaSFormType", type);
    },
    //初始化并获取验证码
    async initCaptcha() {
      const res = await captchaInit();
      if (res.code == 200) {
        this.captchaId = res.data;
        this.imgPicture =
          process.env.VUE_APP_BACK_API +
          "api-auth/common/captcha/draw/" +
          res.data;
      } else {
        this.$message({
          type: "error",
          message: res.status_desc,
        });
      }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          const params = {
            mobile: this.form.mobile,
            password: this.form.password,
            code: this.form.sms_code,
          };
          loginResetPassword(params)
            .then((res) => {
              if (res.code == 200) {
                this.$message.success("修改密码成功");
                this.changeForm("login");
              } else {
                this.$message.error(res.status_desc || "请重试！");
                this.getPicture();
              }
            })
            .catch((e) => {
              this.$message.error(res.status_desc || "请重试！");
              this.getPicture();
              console.log(e);
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    getPicture() {
      //500毫秒内最多获取一次；
      if (this.disabledCatpchaFlash) return;
      this.initCaptcha();
      this.disabledCatpchaFlash = true;
      setTimeout(() => {
        this.disabledCatpchaFlash = false;
      }, 1000);
    },
    stopScrollFun(evt) {
      evt = evt || window.event;
      if (evt.preventDefault) {
        // Firefox
        evt.preventDefault();
        evt.stopPropagation();
      } else {
        // IE
        evt.cancelBubble = true;
        evt.returnValue = false;
      }
      return false;
    }, // 获取短信验证码
    getPhoneMsg(smsType) {
      if (this.disabledVertify) return;
      if (!this.form.mobile) {
        this.$message({
          type: "error",
          message: "请输入手机号码",
        });
        return;
      }
      if (!this.form.code) {
        this.$message({
          type: "error",
          message: "请输入验证码",
        });
        return;
      }
      sendSms({
        mobile: this.form.mobile,
        smsType, //0注册验证码  1登录验证码  2找回密码验证码
        code: this.form.code,
        captchaId: this.captchaId,
      }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "发送验证码成功",
            duration: 3000,
          });
          this.disabledVertify = true;
          if (this.codeInfoText == "发送验证码") {
            let s = 180;
            this.codeInfoText = s + "s";
            let timer = setInterval(() => {
              s -= 1;
              this.codeInfoText = s + "s";
              if (s == 0) {
                this.codeInfoText = "发送验证码";
                this.disabledVertify = false;
                clearInterval(timer);
              }
            }, 1000);
          }
        } else {
          this.$message({
            type: "error",
            message: res.status_desc,
          });
          this.initCaptcha();
        }
      });
    },
  },
};
</script>

<style lang="scss">
</style>

<style lang="scss" scoped>
.passwordInput {
  &.allBorder {
    ::v-deep .el-input__inner {
      border: 1px solid #e3e8ef;
      border-radius: 3px 3px;
    }
  }
  ::v-deep .el-input__inner {
    border-right: 0;
    border-radius: 3px 0px 0px 3px;
  }
  ::v-deep .el-input-group__append {
    border-radius: 2px;
    background: #f4f6fa;
    border: 1px solid #e3e8ef;
    border-left: 0;
    padding: 0;
    width: 42px;
  }
  ::v-deep .el-input-group__append,
  .el-input-group__prepend {
    padding: 0;
  }
  .password-toggle {
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    .password-toggle-img {
      width: 18px;
      height: 18px;
    }
  }
}
.code {
  display: flex;
  align-items: center;
  z-index: 10;
  height: 40px;
  cursor: pointer;
  font-size: 0px;
  img {
    max-width: 100%;
    height: 40px;
  }
}
::v-deep .el-form-item__error {
  font-size: 12px;
  color: #e85e41;
  line-height: 16px;
  text-align: left;
  font-style: normal;
  padding-top: 0px;
  padding-left: 12px;
}
::v-deep .el-input-group__append {
  border-radius: 2px;
  background: #f4f6fa;
  border: 1px solid #e3e8ef;
  padding: 0;
}
.sendCode {
  display: flex;
  justify-content: center;
  width: 100px;
  color: #0b6eff;
}
.bottombuttons {
  ::v-deep .el-button {
    width: 100%;
    height: 32px;
    padding-top: 7px;
    padding-bottom: 7px;
  }
  .changeFormButtons {
    display: flex;
    justify-content: center;
    .changeForm {
      text-align: center;
      cursor: pointer;
      font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
        Microsoft YaHei, Arial, sans-serif;
      font-size: 14px;
      color: #666666;
      line-height: 19px;
      font-style: normal;
      margin: 10px 0 0 0;
      padding: 0 10px;
    }
  }
}
::v-deep .el-form-item {
  margin-bottom: 20px;
}
::v-deep .el-input__inner {
  width: 100%;
  height: 40px;
  background: #f4f6fa;
  border-radius: 3px;
  border: 1px solid #e3e8ef;
}
.code_input {
  ::v-deep .el-input__inner {
    border-radius: 3px 0px 0px 3px;
  }
}

.sms_code_input {
  ::v-deep .el-input__inner {
    border-right: 0;
    border-radius: 3px 0px 0px 3px;
  }
  ::v-deep .el-input-group__append {
    border-radius: 2px;
    background: #f4f6fa;
    border: 1px solid #e3e8ef;
    border-left: 0;
    padding: 0;
    width: 94px;
  }
  ::v-deep .el-input-group__append,
  .el-input-group__prepend {
    padding: 0;
  }
  .sendCode {
    ::v-deep.el-button {
      span {
        padding: 0 12px;
        border-left: 1px solid #e3e8ef;
      }
    }
  }
}
::v-deep .el-form-item.is-error .el-input__inner {
  border-color: #e3e8ef;
}
//删除number的箭头
::v-deep.login-container input::-webkit-outer-spin-button,
::v-deep.login-container input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
::v-deep.login-container input[type="number"] {
  -moz-appearance: textfield;
}
::v-deep.el-input .el-input__inner {
  line-height: 1px !important;
}

@media (max-width: 1440px) {
  .login-block {
    top: 120px !important;
  }
}
</style>
